<template>
  <div class="main">
    <el-form>
      <el-form-item>
        <el-input
            placeholder="请输入课程名称"
            v-model.trim="inputValue"
        >
        </el-input>
      </el-form-item>
      <el-button
          type="primary"
          @click="searchClick"
      >
        搜索
      </el-button>
    </el-form>
    <Table
        :list='courseList'
        :editClick='editClick'
        :deleteHandle='deleteHandle'
    />
    <!-- 分页 -->
    <Pagination
        :currentChange="currentChange"
    />
    <EditPop
        :popShow="popShow"
        v-if="popShow"
        :message="courseItemState.message"
        :confirmClick="confirmClick"
    />
  </div>
</template>

<script setup>
import Table from './Table.vue'
import { reactive, ref, computed,onMounted } from "vue";
import EditPop from "./EditPop.vue";
import { ElMessage } from 'element-plus';
import Pagination from './Pagination.vue';
import {getCourseList,updateCourse,deleteCourse} from '../api/index'
import emitter from "../utils/eventBus";
import { useRouter } from 'vue-router';

const router = useRouter();

/**
 * 初始化数据
 */
const data = reactive({
  list: [],
  page: 1,  // 默认展示第一页
  total: null,
  sideCategory: 'front'
});

/**
 * 课程列表查询的逻辑
 */
 const getCourseData = async (query) => {
  const category = query?.category || data.sideCategory;
  const page = query?.page || 1;
  const pageSize = query?.pageSize || 5;

  console.log('请求课程列表参数:', { category, page, pageSize });

  const res = await getCourseList({category, page, pageSize});

  data.list=res?.data?.list.filter((item) => {
    return item.category === category;
  });
  data.total = res?.data?.total;
}

/**
 * 课程修改接口的调用
 */
const updateCourseData=async (query)=>{
  const {id,title,price}=query
  const res = await updateCourse({id,title,price});
  if (res?.message){
    ElMessage({
      message: '修改成功',
      type: 'success',
    });
  }
}



// 初始化时获取数据
onMounted(async () => {
  if (!localStorage.getItem('token')) {
    router.push('/login');
    return;
  }

  try {
    await getCourseData();
  } catch (error) {
    console.error('初始化课程列表失败:', error);
  }
  
  // 监听分类变化
  emitter.on('course', async (val) => {
    console.log('分类变更为:', val);
    data.sideCategory = val;
    data.page = 1;
    try {
      await getCourseData({ category: val, page: 1 });
    } catch (error) {
      console.error('切换分类获取课程列表失败:', error);
    }
  });
});

/**
 * 分页的逻辑
 */
const currentChange = (val) => {
  if (val === 'pre') {
    if (data.page > 1) {
      data.page--;
    } else {
      ElMessage({
        message: '已经是第一页了',
        type: 'warning',
        showClose: true
      });
    }
  }
  if (val === 'next') {
    if (data.page < Math.ceil(data.total / 5)) { // 向上取整
      data.page++;
    } else {
      ElMessage({
        message: '已经是最后一页了',
        type: 'warning',
        showClose: true
      });
    }
  }
  // 请求课程的接口
  getCourseData({ category: data.sideCategory, page: data.page });
};

/**
 * 搜索框的逻辑
 */
const inputValue = ref('');

// 搜索的逻辑
const courseList = computed(() => {
  console.log('计算课程列表, 当前数据:', data.list);
  if (!data.list || !Array.isArray(data.list)) {
    console.log('课程列表为空或格式不正确');
    return [];
  }
  if (!inputValue.value) {
    return data.list;
  }
  const searchText = inputValue.value.toLowerCase();
  return data.list.filter((item) => {
    return item.title && item.title.toLowerCase().includes(searchText);
  });
});

// 搜索的按钮
const searchClick = () => {
  if (inputValue.value) {
    ElMessage({
      message: '搜索成功',
      type: 'success',
    });
  } else {
    ElMessage({
      message: '请输入搜索内容',
      type: 'error',
    });
  }
};

/**
 * 编辑的逻辑
 */
// 编辑的弹窗显示与隐藏
const courseItemState = reactive({
  message: {}
});
const popShow = ref(false);
const isShowPop = (show) => {
  popShow.value = show;
};

// 编辑的按钮
const editClick = (val) => {
  courseItemState.message = val;
  isShowPop(true);
};

// 确认和取消的逻辑
const confirmClick = (val) => {
  if (val === 'cancel') {
    isShowPop(false);
  } else if (val.title !== courseItemState.message.title || val.price !== courseItemState.message.price) {
    // 修改数据
    data.list.map((item) => {
      if (item.id === val.id) {
        item.title = val.title;
        item.price = val.price;
      }
    });
    // 关闭弹窗
    isShowPop(false);
    // 修改接口的调用
    updateCourseData({
      title: val.title,
      price: val.price,
      id: val.id
    });
  } else {
    ElMessage({
      showClose: true,
      message: '没有修改任何内容',
      type: 'warning',
    });
  }
};

/**
 * 课程删除的逻辑
 */

//课程删除接口的调用
const deleteCourseData=async (query)=>{
  const res = await deleteCourse({id:query});
  if (res?.message){
    ElMessage({
      message: res.message,
      type: 'success',
    });
  }
  // 当前页的数据清零时，重置到该类第一页
  if(data.list.length===0 && data.page>1){
    getCourseData({category:data.sideCategory,page:1})
  }
}

const deleteHandle = async (val) => {
  if (val) {
    // 先从本地数据中移除
    data.list = data.list.filter((item) => item.id !== val);

    try {
      // 发送删除请求
      await deleteCourseData(val);

      // 如果当前页数据为空且页码大于 1，则跳转到第一页
      if (data.list.length === 0 && data.page > 1) {
        await getCourseData({ category: data.sideCategory, page: 1 });
      } else {
        // 否则，刷新当前页数据
        await getCourseData({ category: data.sideCategory, page: data.page });
      }
    } catch (error) {
      console.error('删除课程失败:', error);
      // 删除失败时，恢复本地数据（可选）
      getCourseData({ category: data.sideCategory, page: data.page });


};

    // 删除数据库接口的调用
    deleteCourseData(val)
  }
};
</script>

<style lang='less' scoped>
.el-form {
  display: flex;
}

.main {
  background-color: #fff;
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;

  .input-with-select {
    width: 400px;
    margin-bottom: 40px;
  }
}

:deep(.el-table__header-wrapper) {
  position: fixed;
  z-index: 20;
}

:deep(.el-table__inner-wrapper) {
  overflow: hidden;
}

:deep(.el-table__body-wrapper) {
  margin-top: 40px;
}

:deep(.el-input__inner) {
  width: 300px;
  margin-right: 10px;
}

:deep(.warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9) !important;
  height: 140px !important;
}

.table {
  height: 80vh;
  width: 85vw;
  overflow: hidden;
  overflow-y: scroll;
}

.table::-webkit-scrollbar {
  display: none;
}
</style>
